//数字变化特效
function rollNum(elId, startVal, endVal, decimalNum) {
    let n = decimalNum || 0;
    let countUp = new CountUp(elId, startVal, endVal, n, 2.5, {
        useEasing: true,
        useGrouping: true,
        separator: ',',
        decimal: '.'
    });
    if (!countUp.error) {
        countUp.start();
    } else {
        console.error(countUp.error);
    }
}

var operationSum;
var operationDragSum;
var operationLevelAdjustSum;
var operationStationClick = [];
var topFiveStationName = [];
var topFiveStationNumber = [];
var userIpSum;
var topUserIp = [];
var points = [];
var map;
var heatmapOverlay;
var max_count = -1;

var operation_type_count;


var selectNumber = 10;
initdate();

//获取当天日期
function initdate() {
    const now = new Date();
    const year = now.getFullYear();
    const month = now.getMonth() + 1;
    const day = now.getDate();
    $("#nowDate").html(year + "年" + month + "月" + day + "日");
    console.log("1")
    sseGetData();
    // getData();
    station_click();
};

/**
 * 拿到后端统计数据
 */
function getData() {
    $.ajax({
        // 请求方式为get或者post等
        type: "GET",
        // 服务器响应的数据类型
        dataType: "json",
        //发送的数据
        contentType: "application/json",
        // 请求的url(一般为后台接口)  
        url: "operation/info/" + selectNumber,
        // 请求成功后返回的数据，赋值给变量'data'  
        success: function(data) {
            // console.log("=====获取信息=====");
            // console.log(data);
            if (data.state == "OK") {
                data = data.data;
                operationSum = data.operationSum;
                operationDragSum = data.operationDragSum;
                operationLevelAdjustSum = data.operationLevelAdjustSum;
                operationStationClick = data.operationStationClick;
                topFiveStationName = data.topFiveStationName;
                topFiveStationNumber = data.topFiveStationNumber;
                topUserIp = data.topUserIp;
                userIpSum = data.userIpSum;
                operation_type_count = data.operation_type_count;
                rollNum("userIpSum", 0, userIpSum);
                rollNum("operationSum", 0, operationSum);
                rollNum("operationDragSum", 0, operationDragSum, 2);
                rollNum("operationLevelAdjustSum", 0, operationLevelAdjustSum, 2);
            } else {
                console.log("错误!" + data.state);
            }
            rankEchart();

            station_click();

            point_reli_map();

            OptType();
            //填入数据
            console.log(data);
        },
        error: function(error) {
            console.log("出错!" + error.msg);
        }
    });
}

/**
 * 建立SSE连接 定时拿数据
 */
function sseGetData() {
    let url = "operation/sse/" + selectNumber;
    let source = new EventSource(url);

    //监听从服务器收到的记录
    source.onmessage = function(data) {
            console.log("收到的数据=====》");
            console.log(data);
            data = data.data;
            //转为json
            data = JSON.parse(data);
            operationSum = data.operationSum;
            operationDragSum = data.operationDragSum;
            operationLevelAdjustSum = data.operationLevelAdjustSum;
            operationStationClick = data.operationStationClick;
            topFiveStationName = data.topFiveStationName;
            topFiveStationNumber = data.topFiveStationNumber;
            topUserIp = data.topUserIp;
            userIpSum = data.userIpSum;
            operation_type_count = data.operation_type_count;
            rollNum("userIpSum", 0, userIpSum);
            rollNum("operationSum", 0, operationSum);
            rollNum("operationDragSum", 0, operationDragSum, 2);
            rollNum("operationLevelAdjustSum", 0, operationLevelAdjustSum, 2);
            rankEchart();
            station_click();
            point_reli_map();
            OptType();
            var date = new Date();
            let dateYear = date.getFullYear(); //获取年 
            let dateMonth = date.getMonth(); //获取月  
            let dateDate = date.getDate(); //获取当日
            let dateDay = date.getDay(); //获取当日星期数
            let dateHours = date.getHours(); //获取小时
            let dateMinutes = date.getMinutes(); //获取分钟
            let dateSeconds = date.getSeconds(); //获取秒
            let dateMilliseconds = date.getMilliseconds(); //获取毫秒
            $("#getDate").html(dateHours + ":" + dateMinutes + ":" + dateSeconds);

        }
        //开启回调
    source.onopen = function(event) {
        console.log("浏览器和服务器SSE连接开启");
        //使用ajax去连接
        //第一次
        getData();
        var date = new Date();
        let dateYear = date.getFullYear(); //获取年 
        let dateMonth = date.getMonth(); //获取月  
        let dateDate = date.getDate(); //获取当日
        let dateDay = date.getDay(); //获取当日星期数
        let dateHours = date.getHours(); //获取小时
        let dateMinutes = date.getMinutes(); //获取分钟
        let dateSeconds = date.getSeconds(); //获取秒
        let dateMilliseconds = date.getMilliseconds(); //获取毫秒
        $("#getDate").html(dateHours + ":" + dateMinutes + ":" + dateSeconds);
    }
}


/**
 * 绘制top
 */
function rankEchart() {
    //获取排行数据
    const rankChart = echarts.init(document.getElementById("rankChart"), "shine");
    const rankChartOpt = {
        tooltip: {
            trigger: "axis",
            axisPointer: {
                type: "shadow"
            },
            formatter: function(params) {
                console.log(params);
                const param = params[0];
                const marker =
                    '<span style="display:inline-block;margin-right:5px;border-radius:10px;width:10px;height:10px;background-color:#e6b600;"></span>';
                const suffix = '<span style="margin-left:5px;font-size:12px;"></span>';
                return param.name + "<br />" +
                    marker + "排名：" + (param.dataIndex + 1) + "<br />" +
                    marker + "被点击数：" + param.value + suffix;
            }
        },
        grid: {
            top: 10,
            bottom: 10,
            left: 60
        },
        xAxis: {
            show: false,
            type: "value"
        },
        yAxis: {
            type: "category",
            inverse: true,
            axisLine: {
                show: false
            },
            axisTick: {
                show: false
            },
            axisLabel: {
                fontSize: 12,
                color: "#b0c2f9"
            }
        },
        series: [{
            name: "市价总值排行",
            type: "bar",
            barCategoryGap: "60%",
            label: {
                show: true,
                position: "right",
                fontSize: 12,
                color: "#188df0",
                emphasis: {
                    color: "#e6b600"
                }
            },
            itemStyle: {
                normal: {
                    color: new echarts.graphic.LinearGradient(
                        0, 1, 1, 1, [{
                            offset: 0,
                            color: '#b0c2f9'
                        }, {
                            offset: 0.5,
                            color: '#188df0'
                        }, {
                            offset: 1,
                            color: '#185bff'
                        }]
                    )
                },
                emphasis: {
                    color: new echarts.graphic.LinearGradient(
                        0, 1, 1, 1, [{
                            offset: 0,
                            color: '#b0c2f9'
                        }, {
                            offset: 0.7,
                            color: '#e6b600'
                        }, {
                            offset: 1,
                            color: '#ceac09'
                        }]
                    )
                }
            }
        }]
    };
    rankChart.setOption(rankChartOpt);
    const xData = [];
    const yData = [];
    console.log("--------------");
    console.log(topFiveStationName);
    console.log("---------------");
    topFiveStationName.forEach((element, index) => {
        xData.push(topFiveStationNumber[index]);
        yData.push(element);
    });
    console.log("xData:" + xData);
    console.log("yData:" + yData);
    $("#rankChart").addClass("chart-done");

    rankChart.setOption({
        yAxis: {
            data: yData
        },
        series: [{
            name: "站点点击数量",
            data: xData
        }]
    });
}


//获取地域分布数据
/*
 * 绘制百度热力图
 */
var points = [];

function point_reli_map() {
    map = new BMap.Map("mapChart"); // 创建地图实例
    var point = new BMap.Point(-73.98635, 40.74852); // 创建点坐标
    map.centerAndZoom(point, 14);
    // 开启滚轮缩放
    map.enableScrollWheelZoom(true);
    if (!isSupportCanvas()) {
        alert('热力图目前只支持有canvas支持的浏览器,您所使用的浏览器不能使用热力图功能~')
    }

    map.clearOverlays();
    //绘制百度热力图
    points = [];
    Object.keys(operationStationClick).forEach((index) => {
        let name = index;
        let count = operationStationClick[index];
        if (max_count < count) max_count = count;
        let point = {
            "lng": "",
            "lat": "",
            "count": ""
        };
        // 去查询经纬度
        $.ajax({
            // 请求方式为get或者post等
            type: "GET",
            // 服务器响应的数据类型
            dataType: "json",
            //发送的数据
            contentType: "application/json",
            // 请求的url(一般为后台接口)  
            url: "station/" + name,
            // 请求成功后返回的数据，赋值给变量'data'  
            //执行完毕后再向下执行
            async: false,
            success: function(data) {
                console.log("=====获取信息=====");
                point.lng = data.lon;
                point.lat = data.lat;
                point.count = count;
                console.log(point);
                console.log("===================");
                points.push(point);
            },
            error: function(error) {
                console.log("出错!" + error.msg);
            }
        });
    });
    addMark();
    openHeatmap();
}

function isSupportCanvas() {
    var elem = document.createElement('canvas');
    return !!(elem.getContext && elem.getContext('2d'));
}

function openHeatmap() {
    heatmapOverlay.show();
}

function closeHeatmap() {
    heatmapOverlay.hide();
}

function addMark() {
    //放入到地图中
    heatmapOverlay = new BMapLib.HeatmapOverlay({
        "radius": 100,
        "visible": true
    });
    map.addOverlay(heatmapOverlay);
    console.log("放入");
    console.log(points);
    heatmapOverlay.setDataSet({
        data: points,
        max: max_count
    });
}



//获取所有站点被点击数
var trendChart;

function station_click() {
    trendChart = echarts.init(document.getElementById("trendChart"), "shine");
    const trendChartOpt = {
        tooltip: {
            trigger: "axis",
            axisPointer: {
                type: "none"
            }
        },
        legend: {
            left: "center",
            bottom: 3,
            itemWidth: 15,
            itemHeight: 10,
            textStyle: {
                fontSize: 12,
                color: "#b0c2f9"
            },
            data: ["站点点击数"]
        },
        grid: {
            top: 40,
            bottom: 50,
            left: 60,
            right: 60
        },
        xAxis: {
            type: "category",
            axisLine: {
                lineStyle: {
                    color: "#b0c2f9"
                }
            },
            axisTick: {
                show: false
            },
            axisLabel: {
                fontSize: 12,
                color: "#b0c2f9"
            }
        },
        yAxis: [{
                name: "站点点击数",
                type: "value",
                splitNumber: 5,
                axisLine: {
                    lineStyle: {
                        color: "#b0c2f9"
                    }
                },
                splitLine: {
                    show: false
                },
                axisTick: {
                    color: "#b0c2f9"
                },
                axisLabel: {
                    fontSize: 12,
                    color: "#b0c2f9",
                    formatter: (value, index) => {
                        return parseInt(value) + "次";
                    }
                }
            },
            // {
            //     name: "市盈率",
            //     type: "value",
            //     splitNumber: 5,
            //     maxInterval: 5,
            //     minInterval: 5,
            //     interval: 5,
            //     axisLine: {
            //         lineStyle: {
            //             color: "#b0c2f9"
            //         }
            //     },
            //     splitLine: {
            //         show: false
            //     },
            //     axisTick: {
            //         color: "#b0c2f9"
            //     },
            //     axisLabel: {
            //         fontSize: 12,
            //         color: "#b0c2f9"
            //     }
            // }
        ],
        visualMap: {
            show: false,
            seriesIndex: 2,
            dimension: 0,
            pieces: [{
                lte: 9,
                color: "rgba(176, 58, 91, 1)"
            }, {
                gt: 9,
                lte: 11,
                color: "rgba(176, 58, 91, 0.5)"
            }]
        },
        series: [{
            name: "站点点击数",
            type: "pictorialBar",
            symbol: 'path://d="M150 50 L130 130 L170 130  Z"',
            barCategoryGap: "40%",
            itemStyle: {
                color: function(params) {
                    if (params.dataIndex >= 10) {
                        return "rgba(119, 96, 246, 0.5)";
                    }
                    return "rgba(119, 96, 246, 1)";
                }
            },
        }]
    };
    trendChart.setOption(trendChartOpt);
    GetclickData();
}

function GetclickData() {
    /**
     * 给echarts数据
     */
    const xData = [];
    const yData1 = [];
    Object.keys(operationStationClick).forEach((index) => {
        xData.push(index)
        yData1.push(operationStationClick[index]);
    });
    trendChart.setOption({
        xAxis: {
            data: xData,
        },
        series: [{
                name: "站点点击数",
                data: yData1
            }
            // , {
            //     name: "成交总额",
            //     data: yData2
            // }, {
            //     name: "平均市盈率",
            //     data: yData3
            // }
        ]
    });
    $("#trendChart").addClass("chart-done");
}




/**
 * 饼图分类占比
 */
function OptType() {
    const csrcChart = echarts.init(document.getElementById("csrcChart"), "shine");
    const csrcChartOpt = {
        tooltip: {
            trigger: "item",
            formatter: "{b0}<br />操作数：{c0}<br />占比：{d0}%"
        },
        legend: {
            type: "scroll",
            orient: "vertical",
            padding: 0,
            top: 15,
            right: 0,
            itemGap: 5,
            itemWidth: 10,
            itemHeight: 10,
            textStyle: {
                fontSize: 10,
                color: "#b0c2f9"
            }
        },
        series: [{
            name: "用户操作分类",
            type: "pie",
            center: ["47%", "55%"],
            radius: ["30%", "85%"]
        }]
    };
    csrcChart.setOption(csrcChartOpt);
    // 放入数据
    const chartData = [];
    $("#csrcChart").addClass("chart-done");
    console.log("画出饼图");
    console.log(operation_type_count);
    Object.keys(operation_type_count).forEach(index => {
        console.log(operation_type_count + "," + index);
        if (index == 1) {
            chartData.push({
                name: "拖拽",
                value: operation_type_count[index]
            })
        } else if (index == 2) {
            chartData.push({
                name: "点击",
                value: operation_type_count[index]
            })
        } else if (index == 3) {
            chartData.push({
                name: "滚轮缩放",
                value: operation_type_count[index]
            })
        }
        csrcChart.setOption({
            series: [{
                name: "用户点击分类",
                data: chartData
            }]
        });
    });
}


//浏览器窗口大小变化时，重置报表大小
$(window).resize(function() {
    // rankChart.resize();
    // mapChart.resize();
    // trendChart.resize();
    // csrcChart.resize();
});